package com.chw.common.interceptors;

import com.chw.utils.JWT;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.Map;

@Component//当前类交给ioc管理
public class LogInterceptor implements HandlerInterceptor {
    //重写方法

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)  {
        //获取令牌
        String sign=request.getParameter("token");
        //判断是否有令牌
        if (StringUtils.isEmpty(sign)){
            //没有
            response.setCharacterEncoding("utf-8");
            //响应的数据类型
            response.setContentType("application/json");
            //用流写入
            PrintWriter writer=null;
            try {
                writer=response.getWriter();
            } catch (IOException e) {
                e.printStackTrace();
            }
            writer.write("{\"code\":100,\"msg\":\"没有token\"}");
            writer.close();
            return false;
        }
        //验证token
        Map unsign= JWT.unsign(sign, Map.class);
        if (unsign==null){
            //没有
            response.setCharacterEncoding("utf-8");
            //响应的数据类型
            response.setContentType("application/json");
            //用流写入
            PrintWriter writer=null;
            try {
                writer=response.getWriter();
            } catch (IOException e) {
                e.printStackTrace();
            }
            writer.write("{\"code\":100,\"msg\":\"非法token或没有token\"}");
            writer.close();
            return false;
        }
        return true;
    }
}
